package com.anyikang.volunteer.sos.volunteer.baidu;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.anyikang.volunteer.sos.volunteer.R;
import com.anyikang.volunteer.sos.volunteer.app.MyApplication;
import com.anyikang.volunteer.sos.volunteer.app.MyConstant;
import com.anyikang.volunteer.sos.volunteer.app.bean.EmergencyInfo;
import com.anyikang.volunteer.sos.volunteer.app.bean.MyCurrentOrder;
import com.anyikang.volunteer.sos.volunteer.app.bean.SosPerson;
import com.anyikang.volunteer.sos.volunteer.app.bean.SosPersonData;
import com.anyikang.volunteer.sos.volunteer.app.bean.SosPersonJson;
import com.anyikang.volunteer.sos.volunteer.app.bean.User;
import com.anyikang.volunteer.sos.volunteer.utils.MyErrorDeal;
import com.anyikang.volunteer.sos.volunteer.utils.PermissionResultAdapter;
import com.anyikang.volunteer.sos.volunteer.utils.PermissionUtil;
import com.anyikang.volunteer.sos.volunteer.utils.ToastUtils;
import com.anyikang.volunteer.sos.volunteer.utils.okhttputils_callback.StringDialogCallback;
import com.google.gson.Gson;
import com.lzy.okhttputils.OkHttpUtils;
import com.nostra13.universalimageloader.core.ImageLoader;

import java.util.ArrayList;

import okhttp3.Call;
import okhttp3.Request;
import okhttp3.Response;

/**
 * A simple {@link Fragment} subclass.
 * Activities that contain this fragment must implement the
 * {@link FragmentSosInfo.OnFragmentInteractionListener} interface
 * to handle interaction events.
 * Use the {@link FragmentSosInfo#newInstance} factory method to
 * create an instance of this fragment.
 */
public class FragmentSosInfo extends Fragment implements View.OnClickListener {
    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;
    private View layout;
    private OnFragmentInteractionListener mListener;
    private Activity mActivity;
    private ImageView imvAvatar;
    private TextView tvSosName;
    private TextView tvSosSex;
    private TextView tvSosAge;
    private TextView tvSosAddress;
    private TextView tvSosPhone;
    private TextView tvEmergencyName1;
    private TextView tvEmergencyMobile1;
    private TextView tvEmergencyName2;
    private TextView tvEmergencyMobile2;
    private TextView tvAddress1;
    private TextView tvAddress2;
    private String TAG = "FragmentSosInfo";

    private String sosPersonId;


    public FragmentSosInfo() {
        // Required empty public constructor
    }



    public void setSosPersonId(String sosPersonId) {
        this.sosPersonId = sosPersonId;
    }


    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment BlankFragment2.
     */
    // TODO: Rename and change types and number of parameters
    public static FragmentSosInfo newInstance(String param1, String param2) {
        FragmentSosInfo fragment = new FragmentSosInfo();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        layout = inflater.inflate(R.layout.fragment_sos_person_info, container, false);
        initView();

        initData();
        return layout;
    }


    /**
     * 处理获取信息功
     */
    public void dealGetInfoSuccess(SosPersonJson sosPersonInfo) {

        //解析出数据
        SosPersonData data = sosPersonInfo.getData();
        SosPerson sosPerson = data.getSosPerson();
        String imgUrl = sosPerson.getImageUrl();
        String name = sosPerson.getName();
        int sex = sosPerson.getSex();
        int age = sosPerson.getAge();
        String mobile = sosPerson.getMobile();
        String address = sosPerson.getAddress();
        ArrayList<EmergencyInfo> emergencyInfos = sosPerson.getEmergency();

        //用数据更新UI
        String picUrl = MyConstant.IMAGE_ADDRESS + imgUrl;
        ImageLoader.getInstance().displayImage(picUrl, imvAvatar, MyApplication.optionsForPerson);
        tvSosName.setText(name);
        if (sex == 1) {
            tvSosSex.setText("男");
        } else {
            tvSosSex.setText("女");
        }
        tvSosAge.setText(String.valueOf(age));
        tvSosAddress.setText(address);
        tvSosPhone.setText(mobile);

        int emergencySize = emergencyInfos.size();
        if(emergencySize == 0)
        {
            return;
        }
        else if(emergencySize == 1)
        {
            layout.findViewById(R.id.emergencyLayout1 ).setVisibility(View.VISIBLE);
        }
        else if(emergencySize == 2)
        {
            layout.findViewById(R.id.emergencyLayout1).setVisibility(View.VISIBLE);
            layout.findViewById(R.id.emergencyLayout2).setVisibility(View.VISIBLE);
        }

        //更新紧急联系人
        if (emergencyInfos != null  && emergencySize > 0)
        {
            for(int i = 0; i < emergencySize; i++)
            {

                updataEmergencyContacts(emergencyInfos.get(i),i);
            }
        }
        return;
    }

    public void updataEmergencyContacts(EmergencyInfo emergencyInfo,int index)
    {

        if(index == 0)
        {
            String emergencyName1 = emergencyInfo.getName();
            String emergencyMobile1 = emergencyInfo.getMobile();
            String emergencyAddress1 = emergencyInfo.getAddress();

            if(!TextUtils.isEmpty(emergencyName1))
            {
                tvEmergencyName1.setText(emergencyName1);
            }

            if(!TextUtils.isEmpty(emergencyMobile1))
            {
                tvEmergencyMobile1.setText(emergencyMobile1);
            }

            if(!TextUtils.isEmpty(emergencyAddress1))
            {
                tvAddress1.setText(emergencyAddress1);
            }
        }
        else
        {

            String emergencyName2 = emergencyInfo.getName();
            String emergencyMobile2 = emergencyInfo.getMobile();
            String emergencyAddress2 = emergencyInfo.getAddress();

            if(!TextUtils.isEmpty(emergencyName2))
            {
                tvEmergencyName2.setText(emergencyName2);
            }

            if(!TextUtils.isEmpty(emergencyMobile2))
            {
                tvEmergencyMobile2.setText(emergencyMobile2);
            }

            if(!TextUtils.isEmpty(emergencyAddress2))
            {
                tvAddress2.setText(emergencyAddress2);
            }

        }
        return;

    }


    /**
     * 初始化数据
     */
    private void initData() {

        User user = new User(mActivity);
        String token = user.getUserToken();
        MyCurrentOrder currentOrder = new MyCurrentOrder(mActivity);
        String sosPersonId = currentOrder.getSosPersonId();
        if(TextUtils.isEmpty(sosPersonId))
        {
            return;
        }


        Log.i(TAG,"url ="+ MyConstant.API_SOS_PERSON_INFO + "token="+token+",sosPersonId="+sosPersonId);
        OkHttpUtils
                .get(MyConstant.API_SOS_PERSON_INFO)//
                .tag(MyConstant.API_SOS_PERSON_INFO)//
                .params("tokenId", token)//
                .params("sosPersonId", sosPersonId)//
                .execute(new StringDialogCallback(mActivity) {
                    @Override
                    public void onResponse(boolean isFromCache, String s, Request request, @Nullable Response response) {

                        int retCode = response.code();
                            if(retCode == 200)
                        {
                            Log.i(TAG,"onSuccess 200 return："+s);
                            try
                            {
                                SosPersonJson sosPersonJson = new Gson().fromJson(s,SosPersonJson.class);

                                if(sosPersonJson.getStatus() == 1)//
                                {

                                    dealGetInfoSuccess(sosPersonJson);
                                }
                                else {
                                    String msg = sosPersonJson.getMsg();
                                    MyErrorDeal.dealError(msg,mActivity);
                                }
                            }
                            catch (Exception e)
                            {
                                e.printStackTrace();
                            }
                        }
                        else
                        {
                            MyErrorDeal.dealHttpError(response,mActivity);
                            Log.i(TAG,"onSuccess "+retCode+"return: "+s);
                        }
                    }

                    @Override
                    public void onError(boolean isFromCache, Call call, @Nullable Response response, @Nullable Exception e) {

                        MyErrorDeal.dealHttpError(response,mActivity);

                    }
                });
    }

    /**
     * 初始化视图
     */
    private void initView() {
        imvAvatar = (ImageView) layout.findViewById(R.id.imvAvatar);
        tvSosName = (TextView) layout.findViewById(R.id.tvSosName);
        tvSosSex =(TextView)layout.findViewById(R.id.tvSosSex);
        tvSosAge = (TextView) layout.findViewById(R.id.tvSosAge);
        tvSosAddress = (TextView) layout.findViewById(R.id.tvSosAddress);
        tvSosPhone = (TextView) layout.findViewById(R.id.tvSosPhone);
        tvEmergencyName1 = (TextView) layout.findViewById(R.id.tvEmergencyName1);
        tvEmergencyMobile1 = (TextView) layout.findViewById(R.id.tvEmergencyMobile1);
        tvEmergencyName2 = (TextView) layout.findViewById(R.id.tvEmergencyName2);
        tvEmergencyMobile2 = (TextView) layout.findViewById(R.id.tvEmergencyMobile2);
        tvAddress1 = (TextView) layout.findViewById(R.id.tvAddress1);
        tvAddress2 = (TextView) layout.findViewById(R.id.tvAddress2);

        tvEmergencyMobile1.setOnClickListener(this);
        tvEmergencyMobile2.setOnClickListener(this);
        tvSosPhone.setOnClickListener(this);
    }

    // TODO: Rename method, update argument and hook method into UI event
    public void onButtonPressed(Uri uri) {
        if (mListener != null) {
            mListener.onFragmentInteraction(uri);
        }
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        if (context instanceof OnFragmentInteractionListener) {
            mListener = (OnFragmentInteractionListener) context;
            mActivity = (Activity) context;
        } else {
            throw new RuntimeException(context.toString()
                    + " must implement OnFragmentInteractionListener");
        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }


    /**
     * 拨打救援中心电话号码
     * @param phone
     */
    private void callPhone(final String phone) {
        //6.0权限申请
        PermissionUtil.getInstance().request(mActivity, new String[]{PermissionUtil.PERMISSION_CALL_PHONE}, new PermissionResultAdapter() {
            @Override
            public void onPermissionGranted() {
                // 拨号：激活系统的拨号组件
                Intent intent = new Intent(); // 意图对象：动作 + 数据
                intent.setAction(Intent.ACTION_CALL); // 设置动作
                Uri data = Uri.parse("tel:" + phone); // 设置数据
                intent.setData(data);
                mActivity.startActivity(intent); // 激活Activity组件
            }

            @Override
            public void onPermissionDenied(String... permissions) {
                ToastUtils.showToast(mActivity,"请打开打电话权限");
            }
        });

    }

    @Override
    public void onClick(View view) {

        switch(view.getId())
        {
            case R.id.tvEmergencyMobile1:
                String emergencyPhone1 = tvEmergencyMobile1.getText().toString();

                if(!TextUtils.isEmpty(emergencyPhone1))
                {
                    callPhone(emergencyPhone1);
                }

                break;
            case R.id.tvEmergencyMobile2:

                String emergencyPhone2 = tvEmergencyMobile2.getText().toString();
                if(!TextUtils.isEmpty(emergencyPhone2))
                {
                    callPhone(emergencyPhone2);
                }
                break;
            case R.id.tvSosPhone:

                String sosPersonMobile= tvSosPhone.getText().toString();
                if(!TextUtils.isEmpty(sosPersonMobile))
                {
                    callPhone(sosPersonMobile);
                }
                break;

        }
    }


    /**
     * This interface must be implemented by activities that contain this
     * fragment to allow an interaction in this fragment to be communicated
     * to the activity and potentially other fragments contained in that
     * activity.
     * <p>
     * See the Android Training lesson <a href=
     * "http://developer.android.com/training/basics/fragments/communicating.html"
     * >Communicating with Other Fragments</a> for more information.
     */
    public interface OnFragmentInteractionListener {
        // TODO: Update argument type and name
        void onFragmentInteraction(Uri uri);
    }
}
